<?php
/**
 * Created by PhpStorm.
 * User: a4041
 * Date: 2018/6/13
 * Time: 13:44
 */

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Shop;
use App\Models\ShopDish;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;


Class SearchController extends Controller
{

    // 商家搜索
    public function searchShop(Request $request){
        try{
            $rules = [
                's' => 'required|string',
                'lat'=>'',
                'lng'=>''
            ];
            $validator = Validator::make($request->all(), $rules);
            if ($validator->fails()) {
                return show(202,$validator->errors()->first());
            }
            $mqu = $request->s;
            $lat = $request->lat;
            $lng = $request->lng;
            $perPage = 15;
//            $result = Shop::with(['shopdishes'=>function($query) use($mqu){
//                $query->where('dishes_name','like',"%".$mqu."%");
//            }])->where('is_check',1)
//                ->where('shop_name','like',"%".$mqu."%")
////                ->select('id','shop_name','shop_phone','shop_address','longitude','latitude','shop_pic')
//                ->paginate($perPage);


            //"SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in on clause is ambiguous (SQL: select count(*) as
            // aggregate from `shops` left join `shop_dishes` on `id` = `shop_id` where `is_check` = 1 and `shop_name` like %小%)"
//             select id,shop_name,shop_phone,shop_address,is_takeout,is_reserve,is_list,note

//            DB::enableQueryLog();

            $result = DB::table('shops')->selectRaw("shops.*,shop_info.*,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$lat.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$lat.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$lng.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS distance")
                ->leftJoin('shop_info','shops.id','=','shop_info.shop_id')
                ->where('is_check',1)
                ->where('shop_name','like',"%".$mqu."%")
                ->orderBy('distance','asc')
                ->paginate($perPage);
//            $a  = "select a.* , b.title as btitle from `ims_weisrc_dish_stores`a
//left join `ims_weisrc_dish_goods` b on a.id=b.storeid  WHERE a.is_show=1 AND a.deleted=0  AND a.title like '%平台%'
//OR b.title like '%平台%'  GROUP BY a.id  ORDER BY a.displayorder  DESC,a.id DESC";

//            dd(DB::getQueryLog());
            if ($result->isEmpty()){
                return show(202,'暂无相关信息');
            }
            return show(200,'搜索成功',$result);
        }catch (\Exception $e){
            dd($e->getMessage());
            return show(202,'暂无相关信息');
        }
    }

}